package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/*
地址管理
 */
@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /*
    新增地址
     */
    @PostMapping
    public R addBook(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success(addressBook);
    }

    /*
    默认地址
     */
    @PutMapping("/default")
    public R defaul(@RequestBody AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> qw = new LambdaUpdateWrapper<>();
        qw.set(AddressBook::getIsDefault, 0);
        qw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        System.out.println(BaseContext.getCurrentId());
        addressBookService.update(qw);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    /*
    根据id查询地址
     */
    @GetMapping("/{id}")
    public R byId(@PathVariable Long id) {
        AddressBook byId = addressBookService.getById(id);
        if (byId != null) {
            return R.success(byId);
        } else {
            return R.error("查不到地址");
        }
    }

    @GetMapping("/default")
    public R queryDefault() {
        LambdaUpdateWrapper<AddressBook> qw = new LambdaUpdateWrapper<>();
        qw.eq(AddressBook::getIsDefault, 1);
        qw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        AddressBook one = addressBookService.getOne(qw);
        if (one != null) {
            return R.success(one);
        } else {
            return R.error("查不到地址");
        }
    }

    /*
    根据id查询用户全部地址
     */
    @GetMapping("/list")
    public R list() {
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(qw);
        return R.success(list);
    }

    /*
    删除地址
     */
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }

    /*
    修改地址
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook) {
        addressBookService.updateById(addressBook);
        return R.success("修改成功");

    }


}
